using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;
using UniversalAdmin.Api.Filters;

[ApiController]
[Route("api/menus")]
[Authorize]
public class MenusController : ControllerBase
{
    private readonly IAppMenuService _menuService;
    public MenusController(IAppMenuService menuService) { _menuService = menuService; }

    [HttpGet]
    [RequirePermission("menu.view")] // 需要查看菜单权限
    public async Task<ApiResult> Get([FromQuery] int? page = null, [FromQuery] int? size = null, [FromQuery] string? search = null)
    {
        if (page.HasValue && size.HasValue)
        {
            var result = await _menuService.GetPagedAsync(new PagedQuery { Page = page.Value, Size = size.Value, Search = search });
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
        else
        {
            var result = await _menuService.GetAllAsync(search);
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
    }

    [HttpGet("{id}")]
    [RequirePermission("menu.view")] // 需要查看菜单权限
    public async Task<ApiResult<MenuDto>> GetById(Guid id)
        => await _menuService.GetByIdAsync(id);

    [HttpPost]
    [RequirePermission("menu.create")] // 需要创建菜单权限
    public async Task<ApiResult<MenuDto>> Create([FromBody] CreateMenuDto dto)
        => await _menuService.CreateAsync(dto);

    [HttpPut("{id}")]
    [RequirePermission("menu.edit")] // 需要编辑菜单权限
    public async Task<ApiResult<MenuDto>> Update(Guid id, [FromBody] UpdateMenuDto dto)
        => await _menuService.UpdateAsync(id, dto);

    [HttpDelete("{id}")]
    [RequirePermission("menu.delete")] // 需要删除菜单权限
    public async Task<ApiResult> Delete(Guid id)
        => await _menuService.DeleteAsync(id);

    [HttpPut("{id}/enable")]
    [RequirePermission("menu.edit")] // 需要编辑菜单权限
    public async Task<ApiResult> Enable(Guid id)
        => await _menuService.EnableAsync(id);

    [HttpPut("{id}/disable")]
    [RequirePermission("menu.edit")] // 需要编辑菜单权限
    public async Task<ApiResult> Disable(Guid id)
        => await _menuService.DisableAsync(id);

    [HttpPost("{menuId}/roles")]
    [RequirePermission("menu.manage")] // 需要管理菜单权限
    public async Task<ApiResult> AssignRoles(Guid menuId, [FromBody] AssignMenuRolesDto dto)
    {
        dto.MenuId = menuId;
        return await _menuService.AssignRolesAsync(dto);
    }
} 